/*
 * Copyright (c) 2018. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.mrd.gtimpframe.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageInfo;
import com.mrd.base.Jqgrid;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.gtimp.base.entity.Role;
import com.mrd.gtimpframe.entity.Notice;
import com.mrd.gtimpframe.repository.NoticeMapper;
import com.mrd.gtimpframe.strategy.NoticeRoleMatcher;
import com.mrd.util.JsonBinder;
import com.mrd.util.LoginUtil;
import com.mrd.util.ResponseUtils;

@Service("noticeServiceImpl2")
public class NoticeServiceImpl2 extends NoticeServiceImpl {
    @Resource
    private NoticeMapper noticeMapper;
    @Value("${notice.picture.path}")
    private String picturePath;
    @Value("${notice.picture.path.temp}")
    private String pictureTempPath;
    @Value("${notice.picture.maxSize}")
    private long maxSize;
    @Value("${notice.picture.maxNumber}")
    private long maxNumber;

    /**
     * 获取公告列表
     */
    @Override
    public void getNoticeList(HttpServletResponse response, Jqgrid jqgrid, String edit) {
        List<String> roles = null;
        if (StringUtils.isEmpty(edit)) {//公告列表只取生效的公告
            jqgrid.addRule(new SearchRule("STATE", SearchRuleOption.eq, "1"));
            roles = systemRoleTranslateToNoticeRole();
        } else {//排除逻辑删除的数据
            jqgrid.addRule(new SearchRule("STATE", SearchRuleOption.ne, "2"));
        }
        jqgrid.pageWithMybatis();
        boolean defaultSort = true;//使用默认排序
        if (jqgrid.getOrder() != null) {
            jqgrid.sortWithMybatis();
            defaultSort = false;
        }
        String whereCase = jqgrid.getWhereCase();
        List<Notice> noticeList = noticeMapper.selectByWhereCase(whereCase, defaultSort, roles);
        String[][] appliedRoles = this.getAppliedRoles();
        Map<String, String> roleMap = new HashMap<>();
        for (String[] role : appliedRoles) {
            roleMap.put(role[1], role[0]);
        }
        if (StringUtils.isNotEmpty(edit)) {//将适用角色转换为中文
            noticeList.forEach(notice -> {
                notice.setAppliedRoles(roleMap.get(notice.getAppliedRoles()));
            });
        } else {//根据用户角色修正公告的最新发布状态
            noticeList.forEach(notice -> {
                if ("0".equals(notice.getNewPublish())) {
                    boolean containRole = false;
                    for (Role role : LoginUtil.getLoginUser().getRoles()) {
                        if (notice.getNewPublishRoles().contains(role.getId())) {
                            containRole = true;
                            break;
                        }
                    }
                    if (!containRole) {
                        notice.setNewPublish("1");
                    }
                }
            });
        }
        PageInfo<Notice> pageInfo = new PageInfo<>(noticeList);
        JsonBinder jsonBinder = JsonBinder.buildNonNullBinder();
        jsonBinder.setDateFormat("yyyy-MM-dd HH:mm");
        ResponseUtils.renderJson(response, jsonBinder.toJson(new PageImpl(noticeList, jqgrid.getPage(), pageInfo.getTotal())));
    }

    private List<String> systemRoleTranslateToNoticeRole(){
        List<Role> roleList = LoginUtil.getLoginUser().getRoles();
        List<String> rolesIds = roleList.stream().map(Role::getId).collect(Collectors.toList());
        List<String> noticeRoles = new ArrayList<>();
        if(NoticeRoleMatcher.matchAdmin(rolesIds)){
            noticeRoles.addAll(NoticeRoleMatcher.NoticeRole.allName());
            return noticeRoles;
        }
        for (String rolesId : rolesIds) {
            for (NoticeRoleMatcher.NoticeRole noticeRole : NoticeRoleMatcher.NoticeRole.values()) {
                for (String roleId : noticeRole.getRoleIdArr()) {
                    if(roleId.equals(rolesId)){
                        noticeRoles.add(noticeRole.name());
                        break;
                    }
                }
            }
        }
        noticeRoles.add(NoticeRoleMatcher.NoticeRole.ALL.name());
        return noticeRoles;
    }
}

